#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string>
#include<unistd.h>

int main()
{
    //1.父进程创建管道
    int pipefd[2]={0};
    int n = pipe(pipefd);
    (void)n;
    //2.fork创建子进程
    pid_t id=fork();
    if(id<0)
    {
        perror("fork");
        exit(1);
    }
    else if(id==0)
    {
        //3.父子关闭不需要的fd
        close(pipefd[0]);
        //向管道写数据
        std::string str = "hello my name is zss";
        std::string self = std::to_string(getpid());
        int cnt=0;
        while(true)
        {
            sleep(2);
            std::string message = str +","+self+",";
            message += std::to_string(cnt++);
            message += "\r\n";
            write(pipefd[1],message.c_str(),message.size());

        }
    }
    else{
        close(pipefd[1]);
        while(true)
        {
            char buffer[1024]={0};
            size_t n =read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]=0;
                std::cout<<"client->father# "<<buffer<<std::endl;
            }
        }
        

        int statuse = 0;
        pid_t rid = waitpid(id,&statuse,0);
    }
    //4.正常传递数据
}